package com.common.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.model.User;
import com.common.model.Users;
import com.common.model.WeiboInfo;
import com.common.sqlmanager.*;

public class IndexController extends Controller {
	private SqlManager sqlManager;
	
	 public void index(){
		 this.render("/index/index.jsp");
	  }
	 
	 //获得token
	 public void getAccessToken() throws Exception{
		 getUser();
	 }
	 
	 //获得登录用户个人信息
	 public void getUser() throws Exception{
		 String url = "https://api.weibo.com/2/users/show.json?access_token="+getPara("access_token")+"&uid="+getPara("uid");
		 String result = post(url);	   
	     String idstr = getPara("uid");
	 	   if(idstr!=null){
	 		  List<User> users = User.dao.find("select * from user");
	 		  if(users.size()>0){
	 		  boolean flag = false;//标记数据库中是否已经存在该用户不存在为false
	 		 for(int i = 0; i < users.size(); i++)  
	         {  
	 		if(users.get(i).getStr("idstr").equals(getPara("uid"))){
	 		     flag = true;
	 		     break;
//	             user.update();
	           }  
	         } 
	 		if(!flag){
	 			 User user = parseUser(result);
	 			 user.save();
	 		 }else{
	 			 renderJson(result);
	 		 }
	 		  }else{
	 			  User user = parseUser(result);
	 			  user.save();
	 		  }
	 	   }  
	        
	 }
	 
	private User parseUser(String result) throws Exception{
		User user = JSON.parseObject(result, User.class);
        user.set("access_token",getPara("access_token"));
        user.set("idstr", user.getIdstr());
        user.set("screen_name", user.getScreen_name());
        user.set("name", user.getName());
        user.set("province", user.getProvince());
        user.set("city", user.getCity());
        user.set("location", user.getLocation());
        user.set("description", user.getDescription());
        user.set("url", user.getUrl());
        user.set("profile_image_url", user.getProfile_image_url());
        user.set("domain", user.getDomain());
        user.set("weihao", user.getWeihao());
        user.set("gender", user.getGender());
        user.set("followers_count", user.getFollowers_count());
        user.set("friends_count", user.getFriends_count());
        user.set("statuses_count", user.getStatuses_count());
        user.set("favourites_count", user.getFavourites_count());
        user.set("created_at", user.getCreated_at());
        user.set("verified", user.isVerified());
        user.set("verified_reason", user.getVerified_reason());
        getUsers(result);
        return user;
	 }
	 
	//获得关注用户个人信息
	 public void getUsers(String userInfo) throws Exception{
		 boolean isLastPage = false;
		 sqlManager = SqlManager.shareManager();
		 String sql = "insert into users(idstr,uid,screen_name,description,profile_image_url,gender,followers_count,statuses_count,verified,verified_reason) values(?,?,?,?,?,?,?,?,?,?)";
	   	 Connection connection =  sqlManager.getConnection(sql);
	   	 PreparedStatement cmd = connection.prepareStatement(sql);
		 for(int page = 1;!isLastPage;page++){
	       String url = "http://m.weibo.cn/page/json?containerid=100505"+getPara("uid")+"_-_FOLLOWERS&page="+page;
	       String result = post(url);
	       String count = JSONObject.parseObject(result).getString("count");
	       if(count != null){
	       JSONArray cardsArra = JSONObject.parseObject(result).getJSONArray("cards");  
	       JSONArray arra = cardsArra.getJSONObject(0).getJSONArray("card_group");
	       for(int i = 0;i<arra.size();i++){
	    	JSONObject user = arra.getJSONObject(i).getJSONObject("user");
	    	System.out.println("userid:"+user.getString("id"));
//	        Users users = new Users();
//	        users.set("uid", user.getString("id"));
//	      
//	        users.set("idstr", getPara("uid"));
//	        users.set("screen_name", user.getString("screen_name"));
//	        users.set("description", user.getString("description"));
//	        users.set("profile_image_url", user.getString("profile_image_url"));
//	        users.set("gender", user.getString("gender"));
//	        users.set("followers_count", user.getString("fansNum"));
//	        users.set("statuses_count", user.getString("statuses_count"));
//	        users.set("verified", user.getBoolean("verified"));
//	        users.set("verified_reason", user.getString("verified_reason"));
//	        if(i!=1){//表情储存
//	        	users.save();
//	        }
	   	    cmd.setString(1, getPara("uid"));
   		    cmd.setString(2, user.getString("id"));
   		    cmd.setString(3, user.getString("screen_name"));
   		    cmd.setString(4, user.getString("description"));
   		    cmd.setString(5, user.getString("profile_image_url"));
   		    cmd.setString(6, user.getString("gender"));
   		    cmd.setString(7, user.getString("fansNum"));
   		    cmd.setString(8, user.getString("statuses_count"));
   		    cmd.setBoolean(9, user.getBoolean("verified"));
   		    cmd.setString(10, user.getString("verified_reason"));
   		    cmd.addBatch();
   		    getFriendsWeibo(user.getString("id"));
	    }
   		 cmd.executeBatch(); 
//   		 cmd.close();    
	       }else{
	    	   isLastPage = true;
	       }
		 }
	       
	       renderJson(userInfo);
	       
	 }
	 
	 //获取好友微博
	 public void getFriendsWeibo(String uid) throws Exception{
		 int maxPage = 1;
		 for(int page = 1;page<(maxPage+1);page++){
		    String url = "http://m.weibo.cn/page/json?containerid=100505"+uid+"_-_WEIBO_SECOND_PROFILE_WEIBO&page="+page;
		    String result = post(url);   
		    JSONArray cardsArra = JSONObject.parseObject(result).getJSONArray("cards"); 
		    if(page == 1){
				 maxPage = cardsArra.getJSONObject(0).getIntValue("maxPage");
				 if(maxPage>10){
				  maxPage = 10;
				 }
			 }
		   
		       JSONArray arra = cardsArra.getJSONObject(0).getJSONArray("card_group");
		       if(arra != null){
		       sqlManager = SqlManager.shareManager();
		       String sql = "insert into weiboInfo(idstr,weibo_id,uid,access_token,user_screen_name,user_profile_image_url,created_at,text,source,favorited) values(?,?,?,?,?,?,?,?,?,?)";
			   	 Connection connection =  sqlManager.getConnection(sql);
			   	 PreparedStatement cmd = connection.prepareStatement(sql);
		       for(int i = 0;i<arra.size();i++){ 
		    	JSONObject weibo = arra.getJSONObject(i).getJSONObject("mblog");
		   	    JSONObject user = weibo.getJSONObject("user");
		   	    cmd.setString(1, getPara("uid"));
       		    cmd.setString(2, weibo.getString("idstr"));
       		    cmd.setString(3, user.getString("id"));
       		    cmd.setString(4, getPara("access_token"));
       		    cmd.setString(5, user.getString("screen_name"));
       		    cmd.setString(6, user.getString("profile_image_url"));
       		    cmd.setString(7, weibo.getString("created_at"));
       		    cmd.setString(8, weibo.getString("text"));
       		    cmd.setString(9, weibo.getString("source"));
       		    cmd.setBoolean(10, weibo.getBoolean("favorited"));
       		    cmd.addBatch();
		    }
       		 cmd.executeBatch(); 
       		 cmd.close();   
		       }else{
		    	  page--;
		       } 
		 } 
	 }
	 
	 //获得用户和好友微博
	 public void getWeibo() throws Exception{
		 Db.update("delete from weiboInfo where access_token = ?", getPara("access_token"));
		 //获取自己的微博
		 int maxPage = 1;
		 for(int page = 0;page<(maxPage+1);page++){
		    String url = "http://m.weibo.cn/page/json?containerid=100505"+getPara("uid")+"_-_WEIBO_SECOND_PROFILE_WEIBO&page="+page;
		    String result = post(url);
		    JSONArray cardsArra = JSONObject.parseObject(result).getJSONArray("cards");
		    if(page == 0){
				 maxPage = cardsArra.getJSONObject(0).getIntValue("maxPage");
			 }
		       JSONArray arra = cardsArra.getJSONObject(0).getJSONArray("card_group");
		       
		       sqlManager = SqlManager.shareManager();
		       String sql = "insert into weiboInfo(idstr,weibo_id,uid,access_token,user_screen_name,user_profile_image_url,created_at,text,source,favorited) values(?,?,?,?,?,?,?,?,?,?)";
			   	 Connection connection =  sqlManager.getConnection(sql);
			   	 PreparedStatement cmd = connection.prepareStatement(sql);
			   	 
		       for(int i = 0;i<arra.size();i++){
		    	JSONObject weibo = arra.getJSONObject(i).getJSONObject("mblog");
		   	    WeiboInfo weibos = new WeiboInfo();
		        weibos.set("access_token", getPara("access_token"));
			    weibos.set("idstr", getPara("uid"));
		   	    weibos.set("created_at", weibo.getString("created_at"));
		   	    weibos.set("weibo_id", weibo.getString("idstr"));
		   	    weibos.set("text", weibo.getString("text"));
		   	    weibos.set("source", weibo.getString("source"));
		   	    weibos.set("favorited", weibo.getBoolean("favorited"));
		   	    JSONObject user = weibo.getJSONObject("user");
		   	    weibos.set("uid", user.getString("id"));
		   	    weibos.set("user_screen_name", user.getString("screen_name"));
		        weibos.set("user_profile_image_url", user.getString("profile_image_url"));
		   	    weibos.set("uid", user.getString("id"));
//		   	    weibos.save();
		   	    cmd.setString(1, getPara("uid"));
    		    cmd.setString(2, weibo.getString("idstr"));
    		    cmd.setString(3, user.getString("id"));
    		    cmd.setString(4, getPara("access_token"));
    		    cmd.setString(5, user.getString("screen_name"));
    		    cmd.setString(6, user.getString("profile_image_url"));
    		    cmd.setString(7, weibo.getString("created_at"));
    		    cmd.setString(8, weibo.getString("text"));
    		    cmd.setString(9, weibo.getString("source"));
    		    cmd.setBoolean(10, weibo.getBoolean("favorited"));
    		    cmd.addBatch();
		    }
    		 cmd.executeBatch(); 
    		 cmd.close();    
		 }
		 
		 //获取最新微博
		   String url = "https://api.weibo.com/2/statuses/friends_timeline.json?access_token="+getPara("access_token");
		   String result = post(url);
//		   parseWeibo(result);
	 	   renderJson(result); 
	 }
	 
	 
	 public void parseWeibo(String result){
		 JSONArray arra = JSONObject.parseObject(result).getJSONArray("statuses");
	       for(int i = 0;i<arra.size();i++){
	       	 WeiboInfo weibo = new WeiboInfo();
	       	 weibo.set("access_token", getPara("access_token"));
	         weibo.set("idstr", getPara("uid"));
	         weibo.set("weibo_id", arra.getJSONObject(i).getString("idstr"));
	       	 weibo.set("uid", arra.getJSONObject(i).getJSONObject("user").getString("idstr"));
	       	 weibo.set("user_screen_name", arra.getJSONObject(i).getJSONObject("user").getString("screen_name"));
	       	 weibo.set("user_profile_image_url", arra.getJSONObject(i).getJSONObject("user").getString("profile_image_url"));
	       	 weibo.set("created_at", arra.getJSONObject(i).getString("created_at"));
	       	 weibo.set("text", arra.getJSONObject(i).getString("text"));
	       	 weibo.set("source", arra.getJSONObject(i).getString("source"));
	       	 weibo.set("favorited", arra.getJSONObject(i).getBoolean("favorited")); 
	       	 System.out.println("text:"+arra.getJSONObject(i).getString("text")+"name:"+arra.getJSONObject(i).getJSONObject("user").getString("name"));
//	       	 weibo.save();  
	       }
	 }

//	      // list转Json
//	     public static void list2Json() {
//	          List<Userinfo> list = new ArrayList<Userinfo>();
//	         Userinfo userinfo1 = new Userinfo("lisi", 15);
//	          Userinfo userinfo2 = new Userinfo("wangwu", 16);
//	         list.add(userinfo1);
//	          list.add(userinfo2);
//	          String json = JSON.toJSONString(list, true);
//	          System.out.println("List集合转json格式字符串 :" + json);
//	      }
	 
	 public String post(String url){
		 System.out.println("url:"+url);
		   PrintWriter out = null;
	       BufferedReader in = null;
	       String result = "";
	       try {
	           URL realUrl = new URL(url);
	           // 打开和URL之间的连接
	           URLConnection conn = realUrl.openConnection();
	           // 设置通用的请求属性
	           conn.setRequestProperty("accept", "*/*");
	           conn.setRequestProperty("connection", "Keep-Alive");
	           conn.setRequestProperty("user-agent",
	                   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	           // 发送POST请求必须设置如下两行
	           conn.setDoOutput(true);
	           conn.setDoInput(true);
	           // 获取URLConnection对象对应的输出流
//	           out = new PrintWriter(conn.getOutputStream());
	           // 发送请求参数
//	           out.print(json);
	           
	           // flush输出流的缓冲
//	           out.flush();
	           // 定义BufferedReader输入流来读取URL的响应
	           in = new BufferedReader(
	                   new InputStreamReader(conn.getInputStream()));
	           String line;
	           while ((line = in.readLine()) != null) {
	               result = result+line;
	           }
	       } catch (Exception e) {
	           System.out.println("发送 POST 请求出现异常！"+e);
	           e.printStackTrace();
	       }
	       //使用finally块来关闭输出流、输入流
	       finally{
	           try{
	               if(out!=null){
	                   out.close();
	               }
	               if(in!=null){
	                   in.close();
	               }
	           }
	           catch(IOException ex){
	               ex.printStackTrace();
	           }
	       } 
	       System.out.println("results:"+result);
	       return result;
	 }
	 
}
